<template>
  <div class="app-container flex column">
    <top-title :updateTime="true" :content="content"></top-title>
    <div class="content-wrap f1 flex column">
      <div class="table-operator">
        <a-button @click="handleAdd" type="primary" class="BtnStyle" icon="plus" v-has="'permission:add'">
          新增
        </a-button>
        <a-button @click="handleSave" :loading="loadingSave" type="primary" class="BtnStyle" icon="save">
          保存
        </a-button>
        <a-button @click="batchDel" v-if="selectedRowKeys.length > 0" class="BtnStyle" type="primary" icon="delete">
          批量删除
        </a-button>
      </div>
      <!-- <div class="alter flex align-center" style="margin: 0">
        <img src="@/assets/imgs/alter_icon.png" alt="" />
        <span>已选择:</span>
        <span v-if="selectionRows.length">{{ selectionRows.length }}</span>
        <span v-if="selectionRows.length" @click="onClearSelected">清空</span>
      </div> -->
      <a-tree
        class="draggable-tree"
        :default-expanded-keys="expandedKeys"
        draggable
        :tree-data="dataSource"
        :replaceFields="{ children: 'children', title: 'name', key: 'id' }"
        @dragend="onDragend"
        @drop="onDrop"
      >
        <template #title="record">
          <div>
            <span>{{ record.name }} {{ record.menuType == 2 ? '(按钮)' : '' }}</span>
            <span>
              <a class="operation dropdown-color" @click="handleEdit(record)" v-has="'permission:edit'">编辑</a>
              <a-dropdown v-has="'permission:more'">
                <a class="ant-dropdown-link operation dropdown-color">
                  更多
                  <a-icon type="down" />
                </a>
                <a-menu slot="overlay">
                  <a-menu-item v-has="'permission:detail'">
                    <a href="javascript:;" @click="handleDetail(record)">详情</a>
                  </a-menu-item>
                  <a-menu-item v-has="'permission:addRecord'">
                    <a href="javascript:;" @click="handleAddSub(record)">添加下级</a>
                  </a-menu-item>

                  <a-menu-item v-has="'permission:delete'">
                    <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                      <a>删除</a>
                    </a-popconfirm>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </span>
          </div>
        </template>
      </a-tree>
      <!-- <a-table
        rowKey="id"
        :columns="columns"
        class="tableList"
        :pagination="false"
        :dataSource="dataSource"
        :loading="loading"
        :expandedRowKeys="expandedRowKeys"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @expandedRowsChange="handleExpandedRowsChange"
      >
        <span slot="action" slot-scope="text, record">
          <a class="operation dropdown-color" @click="handleEdit(record)" v-has="'permission:edit'">编辑</a>

          <a-dropdown v-has="'permission:more'">
            <a class="ant-dropdown-link operation dropdown-color">
              更多
              <a-icon type="down" />
            </a>
            <a-menu slot="overlay">
              <a-menu-item v-has="'permission:detail'">
                <a href="javascript:;" @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item v-has="'permission:addRecord'">
                <a href="javascript:;" @click="handleAddSub(record)">添加下级</a>
              </a-menu-item>

              <a-menu-item v-has="'permission:delete'">
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
        <span slot="url" slot-scope="text">
          <j-ellipsis :value="text" :length="25" />
        </span>
        <span slot="component" slot-scope="text">
          <j-ellipsis :value="text" />
        </span>
      </a-table> -->
    </div>
    <permission-modal ref="modalForm" @refresh="modalFormOk"></permission-modal>
    <permission-data-rule-list ref="PermissionDataRuleList" @refresh="modalFormOk"></permission-data-rule-list>
  </div>
</template>

<script>
import { getPermissionList, editPermission } from '@/api/api'
import topTitle from '@/components/topTitle'
import JEllipsis from '@/components/jeecg/JEllipsis'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import PermissionModal from './modules/PermissionModal'
import PermissionDataRuleList from './PermissionDataRuleList'
import { permissionPdataTree } from '../../../api/api'

const x = 3
const y = 2
const z = 1
const gData = []

const generateData = (_level, _preKey, _tns) => {
  const preKey = _preKey || '0'
  const tns = _tns || gData

  const children = []
  for (let i = 0; i < x; i++) {
    const key = `${preKey}-${i}`
    tns.push({ title: key, key })
    if (i < y) {
      children.push(key)
    }
  }
  if (_level < 0) {
    return tns
  }
  const level = _level - 1
  children.forEach((key, index) => {
    tns[index].children = []
    return generateData(level, key, tns[index].children)
  })
}

generateData(z)

export default {
  name: '',
  mixins: [JeecgListMixin],
  components: { topTitle, JEllipsis, PermissionModal, PermissionDataRuleList },
  data() {
    return {
      content: [['菜单管理']],
      url: {
        list: '',
        delete: '/sys/permission/delete',
        deleteBatch: '/sys/permission/delete_batch',
      },
      columns: [
        {
          title: '菜单名称',
          dataIndex: 'name',
          key: 'name',
          align: 'center',
        },
        {
          title: '菜单类型',
          dataIndex: 'menuType',
          align: 'center',
          key: 'menuType',
          customRender: function (text) {
            if (text == 0) {
              return '菜单'
            } else if (text == 1) {
              return '菜单'
            } else if (text == 2) {
              return '按钮/权限'
            } else {
              return text
            }
          },
        },
        /*{
            title: '权限编码',
            dataIndex: 'perms',
            key: 'permissionCode',
          },*/
        {
          title: 'ICON',
          dataIndex: 'icon',
          align: 'center',
          key: 'icon',
        },
        {
          title: '组件',
          dataIndex: 'component',
          align: 'center',
          key: 'component',
          scopedSlots: { customRender: 'component' },
        },
        {
          title: '路径',
          dataIndex: 'url',
          align: 'center',
          key: 'url',
          scopedSlots: { customRender: 'url' },
        },
        {
          title: '排序',
          dataIndex: 'sortNo',
          align: 'center',
          key: 'sortNo',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          scopedSlots: { customRender: 'action' },
          width: 150,
        },
      ],
      loading: false,
      // 展开的行，受控属性
      expandedRowKeys: [],

      gData,
      expandedKeys: ['0-0', '0-0-0', '0-0-0-0'],
      loadingSave: false,
    }
  },
  mounted() {},
  methods: {
    loadData() {
      this.dataSource = []
      getPermissionList().then((res) => {
        if (res.code == 200) {
          this.dataSource = res.result
        }
      })
    },
    handleExpandedRowsChange(expandedRows) {
      this.expandedRowKeys = expandedRows
      // console.log(expandedRows, 'expandedRows')
    },
    // 打开数据规则编辑
    handleDataRule(record) {
      this.$refs.PermissionDataRuleList.edit(record)
    },
    handleAddSub(record) {
      this.$refs.modalForm.title = '添加子菜单'
      this.$refs.modalForm.disableSubmit = false
      this.$refs.modalForm.edit({ status: '1', permsType: '1', route: true, parentId: record.id, menuType: 1 })
    },

    onDragend(info) {
      console.log(info)
      const pos = info.node.pos
      const arr = pos.split('-')
      let lastIndex = arr.at(-1)
      const id = info.node.eventKey
      let sortNode = { ...info.node.dataRef, sortNo: parseInt(lastIndex) }
      // 如果是
      console.log(this.dataSource)
      // 找到哪个节点，然后更改一下 dataSource 的值
      // 拖拽完成之后 截取出 当前 的 order 和 id 之后再调用编辑接口，之后再刷新

      // expandedKeys 需要受控时设置
      // this.expandedKeys = info.expandedKeys
    },

    onDrop(info) {
      const dropKey = info.node.eventKey
      const dragKey = info.dragNode.eventKey
      const dropPos = info.node.pos.split('-')
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
      const loop = (data, key, callback) => {
        data.forEach((item, index, arr) => {
          if (item.id === key) {
            return callback(item, index, arr)
          }
          if (item.children) {
            return loop(item.children, key, callback)
          }
        })
      }
      const data = [...this.dataSource]

      // Find dragObject
      let dragObj
      loop(data, dragKey, (item, index, arr) => {
        arr.splice(index, 1)
        dragObj = item
      })
      if (!info.dropToGap) {
        // Drop on the content
        loop(data, dropKey, (item) => {
          item.children = item.children || []
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.push(dragObj)
        })
      } else if (
        (info.node.children || []).length > 0 && // Has children
        info.node.expanded && // Is expanded
        dropPosition === 1 // On the bottom gap
      ) {
        loop(data, dropKey, (item) => {
          item.children = item.children || []
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.unshift(dragObj)
        })
      } else {
        let ar
        let i
        loop(data, dropKey, (item, index, arr) => {
          ar = arr
          i = index
        })
        if (dropPosition === -1) {
          ar.splice(i, 0, dragObj)
        } else {
          ar.splice(i + 1, 0, dragObj)
        }
      }
      this.dataSource = data
    },

    handleSave() {
      // 最顶层树的 parentId 为空
      function addSortField(node, parentIndex = 0, parentId = '') {
        return node.map((item, index) => {
          item.sortNo = index
          item.parentId = parentId
          //  如果是顶层节点，则将 menutype 设置为0
          if (parentId === '') {
            item.menuType = 0
          } else {
            // 如果不是按钮类型的话
            if (item.menuType !== 2) {
              console.log('更改 menutype 的值')
              item.menuType = 1
            }
          }
          if (item.children) {
            item.leaf = false
            // 如果孩子下面的路由都是隐藏的，则说明也是叶子节点
            // 按钮和 隐藏路由
            // const buttonList = item.children.filter((item) => item.menuType == 2 && item.hidden == false)
            // 有要展示的子路由
            // const routerList = item.children.filter((item) => item.menuType != 2 && item.hidden == true)
            // if (routerList.length === 0) {
            //   item.leaf = true
            // }
            item.children = addSortField(item.children, index, item.id)
          } else {
            item.leaf = true
          }
          return item
        })
      }
      addSortField(this.dataSource)
      this.loadingSave = true
      permissionPdataTree({
        result: this.dataSource,
      })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('保存成功！')
            // 保存成功之后，重新拉取 tree
            this.loadData()
          }
        })
        .finally(() => {
          this.loadingSave = false
        })
    },
  },
  destroy() {},
}
</script>

<style scoped lang="less">
.app-container {
  background: var(--theme-content-bg);
  padding-top: 0;
  .content-wrap {
    background: var(--theme-container-bg);
    padding: 30px 40px;
    overflow: auto;
  }
  /deep/ .ant-tree-node-content-wrapper {
    width: 100%;
  }
  /deep/.ant-tree-title {
    width: 100%;
    > div {
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
